/*
 * @Descripttion: 
 * @version: 
 * @Author: weni09
 * @Date: 2021-04-17 21:42:20
 * @LastEditors: weni09
 * @LastEditTime: 2021-06-11 22:57:21
 * @FilePath: \icoder-frontend\blog\src\utils\axios.js
 */

import Vue from "vue"
import axios from 'axios';
import store from '@/store';

const BASEURL = process.env.NODE_ENV === 'production' ? process.env.VUE_APP_API : process.env.VUE_APP_API_DEV;
const service = axios.create({
    baseURL: BASEURL,
    timeout: 20000,
});


// http request 拦截器
service.interceptors.request.use(
  config => {
    config.headers.Authorization = 'Bearer ' + store.getters.auth.token;
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// http response 拦截器
service.interceptors.response.use(
  // undefined,
  response => {
    const res = response.data
    res.statusCode= response.status
    // console.log(res)
    // if the custom code is not 20000, it is judged as an error.
    // console.log(res.code !== 'success' || response.status < 200 || response.status > 300)
    if(res.hasOwnProperty('user_id') && res.user_id==0){
      store.commit('SET_AUTH',{})
    }
    if (response.status >= 200 && response.status <= 300){
      // if (res.code == 'failed' || res.code == 'exception') {
      //   return Promise.reject(new Error(res.msg || 'Error'))
      // } else{
      return res
      // }
    }
    else{
      return Promise.reject(new Error(res.message || 'Error'))
    }
  },
  error => {
    // const status = response.status
    console.log('err' + error) // for debug
    return Promise.reject(error)
  },
  
  );
Vue.prototype.$http = service

export default service;